package it.blog.controller;

import java.io.IOException;
import java.util.List;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import it.blog.stub.*;


public class PostView extends HttpServlet{

	
		
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		HttpSession session =  request.getSession();
		BlogPortal bp = new BlogPortalService().getPort(BlogPortal.class);
		
		Integer blogID = Integer.parseInt(request.getParameter("blogID"));
		Integer postID = Integer.parseInt(request.getParameter("postID"));
		
		Post post = bp.getPost(postID);
		List<Comment> comments = null;
		comments = bp.getCommentsOfPost(blogID, postID);
		session.removeAttribute("mess");
		if(post!=null){
			
			request.getSession().setAttribute("post",post);
			request.getSession().setAttribute("comments",comments);
			request.getSession().setAttribute("blogOwner",bp.getBlog(blogID).getBlogOwner());
			request.getSession().setAttribute("blogID",blogID);
			
			//PAGINATION
			Integer currentPage= Integer.parseInt(request.getParameter("p"));
			int itemForPage=4;
			int nPage=(int)Math.ceil(((double)comments.size()/itemForPage));
			int first=(currentPage-1)*itemForPage;
			int last=first+itemForPage-1;
			int vect[]={currentPage,nPage,first,last};
			session.setAttribute("paginationComment", vect);
			response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/home.jsp?kop=post"));			
		}else{
			session.setAttribute("mess","visualizzazione post fallita");
			
			response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/home.jsp?kop=post"));
		}
	}







}
